//
//  RootViewController.m
//  iMadeCoreData
//
//  Created by Edward Knutson on 10/13/09.
//  Copyright Six Four Systems 2009. All rights reserved.
//

#import "RootViewController.h"
#import "CJSONDeserializer.h"
#import "Group.h"
#import "GroupDAO.h"
#import "Location.h"
#import "Tag.h"
#import "TransferGroup.h"

@implementation RootViewController

@synthesize dao, groupArray, groupCell, logoArray, managedObjectContext; //, fetchedResultsController;


- (void)viewDidLoad {
    [super viewDidLoad];
	/*
	// Set up the edit and add buttons.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject)];
    self.navigationItem.rightBarButtonItem = addButton;
    [addButton release];
	
	NSError *error;
	if (![[self fetchedResultsController] performFetch:&error]) {
		// Handle the error...
	}
	*/
	self.title = @"iMade Core Data";
	UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] 
									  initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
									  target:self action:@selector(loadOpml)];
	self.navigationItem.leftBarButtonItem = refreshButton;
	[refreshButton release];
	
	self.dao = [[GroupDAO alloc] initWithContext:managedObjectContext];
	[dao release];
		
	self.logoArray = [[NSMutableArray alloc] init];
	[logoArray release];
	
	[self initData];
//	[self loadOpml];
}


- (void)initData {
	NSError *error;
	NSMutableArray *groupArr = [NSMutableArray alloc];
	NSArray *groups = [dao groups:&error];
	if(groups != nil) {
		self.groupArray = [groupArr initWithArray:groups];
		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
		for(int i=0; i<[groups count]; i++) {
			Group *group = [groups objectAtIndex:i];
			[logoArray addObject:[self loadImage:group.logoUrl]];
		}
		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	}
	else self.groupArray = [groupArr init];
	[groupArr release];
	[self.tableView reloadData];
}


- (id)loadImage:(NSString *)url {
	if(url == nil)
		return [NSNull null];
	NSURL *imgUrl = [NSURL URLWithString:url];
	NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
	UIImage *logo = [UIImage imageWithData:imgData];
	if(logo == nil)
		return [NSNull null];
	return logo;
}


- (void)loadOpml {
	NSError *error = nil;
	NSURL *url = [NSURL 
				  URLWithString:@"http://services.mygroupsapp.com/Data/Groups?feedUrl=http://www.theresgonnabesnacks.com/data/mygroups.opml"];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	NSString *opml = [[NSString alloc]
					  initWithContentsOfURL:url
					  encoding:NSUTF8StringEncoding error:&error];
	if(error == nil) {
		if(opml != nil) {
			opml = [NSString stringWithFormat:@"{\"json\":%@}", opml];
			NSData *inData = [opml dataUsingEncoding:NSUTF8StringEncoding];
			NSDictionary *json = [[CJSONDeserializer deserializer] deserializeAsDictionary:inData error:&error];
			if(error == nil) {
				if(json != nil) {
					[groupArray removeAllObjects];
					[logoArray removeAllObjects];
					NSArray *groups = [json valueForKey:@"json"];
					for(int i=0; i<[groups count]; i++) {
						TransferGroup *xfer = [[TransferGroup alloc] initWithDictionary:[groups objectAtIndex:i]];
						[dao saveGroup:xfer error:&error];
						if(error != nil)
							NSLog(@"error saving group: %@", error);
						[xfer release];
					}
				} else NSLog(@"JSON is nil, OPML=%@", opml);
			} else NSLog(@"could not parse JSON: %@", error);
		} else NSLog(@"OPML is nil");
	} else NSLog(@"could not open URL: %@", error);
	NSArray *groups = [dao groups:&error];
	if(groups != nil) {
		[groupArray addObjectsFromArray:groups];
		for(int i=0; i<[groups count]; i++)
			[logoArray addObject:[self loadImage:[[groups objectAtIndex:i] logoUrl]]];
	} else NSLog(@"could not reload groups: %@", error);
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	[self.tableView reloadData];
}

- (void)insertNewObject {
	/*
	// Create a new instance of the entity managed by the fetched results controller.
	NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
	NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
	NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
	
	// If appropriate, configure the new managed object.
	[newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
	
	// Save the context.
    NSError *error;
    if (![context save:&error]) {
		// Handle the error...
    }
	*/
    [self.tableView reloadData];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release anything that can be recreated in viewDidLoad or on demand.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return [[fetchedResultsController sections] count];
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	/*
	id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
	*/
	return [groupArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"GroupCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		[[NSBundle mainBundle] loadNibNamed:@"GroupCell" owner:self options:nil];
        cell = groupCell;
        self.groupCell = nil;
	}
    
	// Configure the cell.
/*
	NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];

	cell.textLabel.text = [[managedObject valueForKey:@"timeStamp"] description];
*/	
	Group *group = [groupArray objectAtIndex:indexPath.row];
	
	// Tag 1: Name
	UILabel *label = (UILabel *)[cell viewWithTag:1];
	label.text = group.name;
	
	// Tag 2: IcsUrl
	label = (UILabel *)[cell viewWithTag:2];
	label.text = group.icsUrl;
	
	// Tag 3: Description
	label = (UILabel *)[cell viewWithTag:3];
	label.text = group.groupDescription;

	// Tag 4: RssUrl
	label = (UILabel *)[cell viewWithTag:4];
	label.text = group.rssUrl;

	// Tag 5: ServicesUrl
	label = (UILabel *)[cell viewWithTag:5];
	label.text = group.servicesUrl;

	// Tag 6: Location
	if(group.location != nil) {
		label = (UILabel *)[cell viewWithTag:6];
		Location *loc = group.location;
		label.text = [NSString stringWithFormat:@"lat: %@, long: %@", loc.latitude, loc.longitude];
	}

	// Tag 7: Tags
	label = (UILabel *)[cell viewWithTag:7];
	NSArray *tags = [group.tags allObjects];
	if(tags != nil && [tags count] > 0) {
		NSMutableString *tagStr = [[NSMutableString alloc] initWithString:[[tags objectAtIndex:0] name]];
		for(int i=1; i<[tags count]; i++) {
			[tagStr appendFormat:@", %@", [[tags objectAtIndex:i] name]];
		}
		label.text = tagStr;
	}

	// Tag 2: Description
	id logo = [logoArray objectAtIndex:indexPath.row];
	if(![[NSNull null] isEqual:logo]) {
		UIImageView *logoView = (UIImageView *)[cell viewWithTag:8];
		logoView.image = logo;
	}

	return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 316.0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here -- for example, create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
    // NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
    // Pass the selected object to the new view controller.
    /// ...
	// [self.navigationController pushViewController:anotherViewController animated:YES];
	// [anotherViewController release];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


// Override to support editing the table view.
/*
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the managed object for the given index path
		NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
		[context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];
		
		// Save the context.
		NSError *error;
		if (![context save:&error]) {
			// Handle the error...
		}
		
		[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
}
*/


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // The table view should not be re-orderable.
    return NO;
}


/*
// NSFetchedResultsControllerDelegate method to notify the delegate that all section and object changes have been processed. 
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
	[self.tableView reloadData];
}
*/


- (void)dealloc {
	[managedObjectContext release];
    [super dealloc];
}


@end

